<?php

namespace app\controllers;

use Yii;
use app\models\Qa;
use app\models\Attention;
use app\controllers\BaseController;

class AttentionController extends BaseController {

    public function actionIndex() {
        return $this->render('index');
    }

    public function actionAdd($qid) {
        if (Yii::$app->user->isGuest) {
            return json_encode(['error' => '请登录']);
        }

        //检查该问答是否存在
        $result = Qa::findOne(['id' => $qid]);
        if ($result) {
            $attention = new Attention();
            $attention->uid = Yii::$app->user->identity->id;
            $attention->qid = $qid;
            $attention->save();
            return json_encode(['success' => '关注成功']);
        }
    }

    public function actionCancel($qid) {
        if (Yii::$app->user->isGuest) {
            return json_encode(['error' => '请登录']);
        }

        //检查该问答是否存在
        $result = Qa::findOne(['id' => $qid]);
        if ($result) {
            $attention = Attention::findOne(['uid' => Yii::$app->user->identity->id, 'qid' => $qid]);
            $attention->delete();
            return json_encode(['success' => '取消关注成功']);
        }
    }

}
